<?php

/**
 * @Author: king
 * @Date:   2019-05-04 16:57:03
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-26 10:57:18
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;
class LanmeiCounselorExerciseRecord extends Base
{
    const CounselorExerciseRecord = ':counselor:exercise:record';
    const TAG = 'counselor_exercise';
    const CACHE_TIME = 86400 * 7;
    protected $table = 'counselor_exercise_record';


    /**
     * 保存用户习题通关状态
     * @param array $data
     * @return array|bool|false|int
     */
    public function saveUserExerciseRecord($data = [])
    {
        try {
            $res = $this->updateOrInsert($data);
        } catch (\Exception $e) {
           throw new ApiException('答题记录保存失败', config('code.error'));
        }

        $start_time = strtotime(date('Y-m-d', time()) . ' 00:00:00');
        Cache::forget($data['uid'] . self::CounselorExerciseRecord . $start_time);
        return $res;
    }

    /**
     * 获取用户今天习题次数
     * @param int $uid
     * @return bool|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getUserExerciseRecord($uid = 0)
    {
        $data = false;
        $start_time = strtotime(date('Y-m-d', time()) . ' 00:00:00');
        $end_time = strtotime(date('Y-m-d', time()) . ' 23:59:59');
        // if ($this->cache_on >= 1) {
        //     $data = Cache::get($uid . self::CounselorExerciseRecord . $start_time);
        // }

        if ($data === false) {
            // $where = [
            //     'uid' => $uid,
            //     'create_time' => ['between', [$start_time, $end_time]]
            // ];
              $where = [
                'uid' => $uid,
              ];
            try {
                $data = $this->where($where)->whereBetween('create_time', [$start_time, $end_time])->get();
                $data = json_decode(json_encode($data, true), true);
                if ($this->cache_on >= 1) {
                    Cache::tags($uid . self::TAG)->set($uid . self::CounselorExerciseRecord . $start_time, $data, self::CACHE_TIME);
                }
            } catch (\Exception $e) {
                throw new ApiException('获取用户习题状态失败', config('code.error'));
            }
        }

        return $data;
    }
}